package com.springboot.demo.controller;

import com.springboot.demo.core.shiro.ShiroUtils;
import com.springboot.demo.util.MD5Utils;
import com.springboot.demo.util.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("login")
public class LoginController {

    private static final String prefix = "springboot/user";

    @RequestMapping("")
    String welcome(){
        return "/login";
    }

    @GetMapping("/login")
    String login() {
        return "/login";
    }

    //requestMapping：理解为一种原始写法，以下为升级版写法
    //@GetMapping是一个组合注解，是@RequestMapping(method = RequestMethod.GET)的缩写。
    //@PostMapping是一个组合注解，是@RequestMapping(method = RequestMethod.POST)的缩写。
    @GetMapping("user")
    String index(){
        return prefix + "/list";
    }

    @PostMapping("/ajaxLogin")
    @ResponseBody
    R ajaxLogin(String email, String password){
        password = MD5Utils.encrypt(email, password);
        UsernamePasswordToken token = new UsernamePasswordToken(email, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return R.ok();
        } catch (AuthenticationException e) {
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }
}
